import { ExceptionFilter, HttpException, ArgumentsHost } from '@nestjs/common';
import { Response, Request } from 'express';

export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly customMessages?: Record<number, string>) {}
  //定义异常文字提示
  private readonly exceptionMessages: Record<number, string> = {
    400: '内部错误，请检查输入',
    401: '令牌过期或无效，请重新登录',
    403: 'Forbidden',
    404: 'Not Found',
    500: 'Internal Server Error',
  };
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message:
        this.customMessages?.[status] ||
        this.exceptionMessages[status] ||
        exception.message,
    });
  }
}
